正規表現を使ってadd dateのCodeLensを作る処理
code:3. ドキュメントを解析して、CodeLens を表示しよう より.ts
while ((matches = regex.exec(text)) !== null) {
// 見出しが見つかった行を抽出し、
// その範囲をレンジとして切り出す
const line = document.lineAt(document.positionAt(matches.index).line);
const indexOf = line.text.indexOf(matches0); const position = new vscode.Position(line.lineNumber, indexOf);
const range = document.getWordRangeAtPosition(
position,
new RegExp(titleRegex)
);
if (range) {
// この範囲に対するCodeLensを作成する
codeLenses.push(
new vscode.CodeLens(range, {
title: "add date",
tooltip: "add date",
})
);
}
}
lineの取り出し
改行文字が改行として見える状態ではなく、ひとつながりの文字列としてindexが"何行目何文字目か"
indexOfを取得=マッチした文字列(matches[0])がlineの何文字目から始まるか
(カーソルを置ける位置のような理解)
positionからtitleRegexに一致するrangeを取得
rangeはundefinedになりうるからif文
これで# sの行の# が取得できる!
感想:rangeの取得はけっこう大変な処理
rangeを使ってCodeLensを作る
rangeにコマンドを結びつけ